package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    //注入对象使得当前类成为消息的生产者（发送者）
    @Autowired
    private MqttProducer mqttProducer;




    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }

    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId, VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }

    //新建工单
    @Override
    @Transactional
    public Boolean addTask(TaskViewModel taskViewModel) {
        //0.校验是否存在正在进行中的同类型共工单；
        if (hasTask(taskViewModel.getInnerCode(), taskViewModel.getProductType())) {
            throw new LogicException("该设备已存在同类型的未完成的工单");
        }
        //1.判断售货机是否存在
        VmVO vm = vmService.getVMInfo(taskViewModel.getInnerCode());
        if (vm == null) {
            throw new LogicException("售货机不存在");
        }
        //1.1校验售货机状态和工单类型是否对应
        checkVmStatus(vm.getVmStatus(), taskViewModel.getProductType());
        //2.判断执行人是否存在
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if (user == null) {
            throw new LogicException("指定的工单执行人员不存在");
        }
        //3.判断工单类型，并进行相应操作
        TaskEntity task = new TaskEntity();
        //生成工单编号
        task.setTaskCode(generateTaskCode());
        task.setTaskStatus(VMSystem.TASK_STATUS_CREATE);//工单状态
        task.setProductTypeId(taskViewModel.getProductType());//工单类型
        task.setAddr(vm.getNodeAddr());//地址
        task.setRegionId(vm.getRegionId());//区域
        task.setUserName(user.getUserName());//用户名
        BeanUtils.copyProperties(taskViewModel, task);
        this.save(task);
        //更新分数
        updateTaskZSet(task,1);
     if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_SUPPLY) {
            //3.2如果是补货工单，就从vo类中提取details属性（工单详情），通过循环插入到工单详情表中
            List<TaskDetailsViewModel> details = taskViewModel.getDetails();
            for (TaskDetailsViewModel detail : details) {
                TaskDetailsEntity taskDetail = new TaskDetailsEntity();
                BeanUtils.copyProperties(detail, taskDetail);
                //设置工单id
                taskDetail.setTaskId(task.getTaskId());
                taskDetailsService.save(taskDetail);
            }
        }
        //4.返回结果
        return true;

    }

    //接收工单
    @Override
    public boolean acceptTask(String taskId) {
        //1。根据id获取task对象
        Long id = Long.valueOf(taskId);
        TaskEntity task = taskService.getById(id);
        //2.如果工单状态不是待处理，抛出异常
        if (!task.getTaskStatus().equals(VMSystem.TASK_STATUS_CREATE)) {
            throw new LogicException("该工单不处于待处理状态");
        }
        //3.修改订单状态为正在进行
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        //4.保存并返回
        return taskService.updateById(task);
    }

    //取消工单
    @Override
    public boolean cancelTask(String taskId, CancelTaskViewModel cancelTaskViewModel) {
        //1.根据id取得工单对象
        TaskEntity task = taskService.getById(Long.valueOf(taskId));
        //2.如果工单状态是已取消或者已完成，抛出异常
        if (task.getTaskStatus().intValue() == VMSystem.TASK_STATUS_CANCEL ||
                task.getTaskStatus().intValue() == VMSystem.TASK_STATUS_FINISH) {
            throw new LogicException("该工单已完成或已取消");
        }
        //3.修改工单状态为取消，记录拒绝原因
        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        task.setDesc(cancelTaskViewModel.getDesc());
            //更新分数
        updateTaskZSet(task,-1);
        //4.更新并返回
        return taskService.updateById(task);
    }

    //完成工单
    @Override
    public boolean completeTask(Long id) {
        TaskEntity task = taskService.getById(id);
        //1.如果工单状态为已完成或已取消，抛出异常
        if (task.getTaskStatus().intValue() == VMSystem.TASK_STATUS_FINISH ||
                task.getTaskStatus().intValue() == VMSystem.TASK_STATUS_CANCEL) {
            throw new LogicException("订单已完成或已取消");
        }
        //2.设置工单状态为已完成；
        task.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        //
        taskService.updateById(task);
            //2.1如果是运维工单，更新完工单状态后，通知售货机微服务，修改售货机状态；
        if (task.getProductTypeId().intValue() ==VMSystem.TASK_TYPE_DEPLOY ||
                task.getProductTypeId().intValue() ==VMSystem.TASK_TYPE_REVOKE){
            noticeVMStatus(task);//运维工单封装下发,通知售货机服务更新售货机状态；
        }
        if(task.getProductTypeId().intValue()==VMSystem.TASK_TYPE_SUPPLY){
            noticeVMSupply(task);
        }

        //3.更新并返回
        return true;
    }

    /**
     * 运维工单完成后，发送消息，通知售货机服务，更新售货机状态
     * @param task
     */
    private void noticeVMStatus(TaskEntity task) {
        //向消息队列发送消息
        //1.封装协议
        TaskCompleteContract taskCompleteContract=new TaskCompleteContract();
        taskCompleteContract.setInnerCode(task.getInnerCode());
        taskCompleteContract.setTaskType(task.getProductTypeId());
        //2.发送消息
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC,2,taskCompleteContract);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.error("运维工单下发出错");
        }
    }

    /**
     * 补货工单完成后，发送消息，通知售货机服务，更新售货机货道信息；
     * @param task
     */
    private void noticeVMSupply(TaskEntity task){
        //1.根据工单id查询工单明细表
        List<TaskDetailsEntity> taskDetails= taskDetailsService.getByTaskId(task.getTaskId());
        //2.构建协议属性
        SupplyContract supplyContract=new SupplyContract();
        supplyContract.setInnerCode(task.getInnerCode());
        //2.2从detail中获取并设置
        List<SupplyChannel> supplyChannels=new ArrayList<>();
        taskDetails.forEach(e->{
            SupplyChannel channel=new SupplyChannel();
            channel.setChannelId(e.getChannelCode());//设置货道编号
            channel.setCapacity(e.getExpectCapacity());//设置容量
            supplyChannels.add(channel);
        });
        supplyContract.setSupplyData(supplyChannels);
        //3.发送消息
        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC,2,supplyContract);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.error("补货工单下发出错");
        }
    }

    //生成工单编号
    private String generateTaskCode() {
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key = "lkd.task.code." + date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().set(key, String.valueOf(1L), Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(Objects.requireNonNull(redisTemplate.opsForValue().increment(key, 1)).toString(), 4, '0');
    }

    //校验售货机和工单状态是否对应
    private void checkVmStatus(int vmStatus, int productType) {
        //如果是投放工单，状态不能为运营状态
        if (productType == VMSystem.TASK_TYPE_DEPLOY && vmStatus == VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("要投放的设备已经在运营中");
        }

        //如果是补货工单，状态必须是运营状态
        if (productType == VMSystem.TASK_TYPE_SUPPLY && vmStatus != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("要补货的设备不在运营状态");
        }

        //如果是撤机工单，状态必须是运营状态
        if (productType == VMSystem.TASK_TYPE_REVOKE && vmStatus != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("要撤机的设备已不在运营状态");
        }
    }

    //校验同一台设备是否有真该进行的未完成的同类型工单
    private boolean hasTask(String innerCode, int productType) {
        LambdaQueryWrapper<TaskEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode, innerCode)
                .eq(TaskEntity::getProductTypeId, productType)
                .eq(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        return this.count(queryWrapper) > 0;
    }


    /**
     * 创建工单时，更新执行人在redis中的分数；
     * @param task
     * @param score
     */
    private void updateTaskZSet(TaskEntity task, int score){
        String roleCode="1003";//运维人员
        if(task.getProductTypeId().intValue()==VMSystem.TASK_TYPE_SUPPLY){
            //如果是补货工单，将角色码设置为1002（运营人员）
            roleCode="1002";
        }
        String key=VMSystem.REGION_TASK_KEY_PREF
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                +"."+task.getRegionId()+"."+roleCode;
        redisTemplate.opsForZSet().incrementScore(key,task.getUserId(),score);

    }

    /**
     * 获取工单量最少的用户
     * @param reginId  区域id
     * @param isRepair  是否是运维人员
     * @return
     */
    @Override
    public int getLeastUser(Long reginId, boolean isRepair) {
        String roleCode="1002"; //运营人员
        if(isRepair){
            roleCode="1003"; //运维人员
        }
        String key=VMSystem.REGION_TASK_KEY_PREF
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                +"."+reginId+"."+roleCode;
        Set<Object> set = redisTemplate.opsForZSet().range(key, 0, 0);//取第一个
        if(set==null||set.isEmpty()){
            return 0;
        }
        //返回第一条
        return (Integer) set.stream().collect(Collectors.toList()).get(0);
    }

}
